Kotlin
Data Classes
Swift
|
data class User(val name: String, val age: Int)
|
data class User(let name: String, let age: Int)
|
data class User(val name: String = "", val age: Int = 0)
|
data class User(let name: String = "", let age: Int = 0)
|
Properties Declared in the Class Body
|
data class Person(val name: String) {
var age: Int = 0
}
|
data class Person(let name: String) {
var age: Int = 0
}
|
val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20
|
let person1 = Person("John")
let person2 = Person("John")
person1.age = 10
person2.age = 20
|
Copying
|
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
|
func copy(name: String = this.name, age: Int = this.age) = User(name, age)
|
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
|
let jack = User(name = "Jack", age = 1)
let olderJack = jack.copy(age = 2)
|
var userJack = User(name="Jack")
var address = Address(user = userJack, city = "London")
var addressCopy = address.copy()
addressCopy.city = "New York"
addressCopy.user.name = "John" // Propagates to `address.user` because they both point to userJack.
|
var userJack = User(name="Jack")
var address = Address(user = userJack, city = "London")
var addressCopy = address.copy()
addressCopy.city = "New York"
addressCopy.user.name = "John" // Propagates to `address.user` because they both point to userJack.
|
Data Classes and Destructuring Declarations
|
val jane = User("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age"
|
let jane = User("Jane", 35)
let (name, age) = jane
print("$name, $age years of age") // prints "Jane, 35 years of age"
|